package com.example.controller;

import com.example.domain.dto.pricing.*;
import com.example.exception.ApiResponse;
import com.example.service.PromotionService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

/**
 * 促销规则管理Controller
 * 
 * <p>提供促销规则的管理接口，包括：
 * <ul>
 *   <li>单品折扣规则管理</li>
 *   <li>满减折扣规则管理</li>
 *   <li>规则启用/禁用</li>
 *   <li>规则查询</li>
 * </ul>
 * </p>
 * 
 * @author Means
 * @since 2025-10-28
 */
@Slf4j
@RestController
@RequestMapping("/api/promotions")
@RequiredArgsConstructor
public class PromotionController {
    
    private final PromotionService promotionService;
    
    // ==================== 单品折扣规则管理 ====================
    
    /**
     * 创建单品折扣规则
     * 
     * @param request 创建单品折扣请求
     * @return 单品折扣规则DTO
     */
    @PostMapping("/item-discounts")
    public ApiResponse<ItemDiscountRuleDTO> createItemDiscount(
            @Valid @RequestBody CreateItemDiscountRequest request) {
        log.info("创建单品折扣规则: name={}, productId={}, discountRate={}", 
                request.getName(), request.getProductId(), request.getDiscountRate());
        
        ItemDiscountRuleDTO rule = promotionService.createItemDiscount(
                request.getName(),
                request.getProductId(),
                request.getDiscountRate(),
                1,  // Priority 1 (商品级，系统自动分配)
                request.getEffectiveFrom(),
                request.getEffectiveTo()
        );
        
        log.info("单品折扣规则创建成功: ruleId={}", rule.getId());
        return ApiResponse.success(rule);
    }
    
    /**
     * 查询所有单品折扣规则
     * 
     * @return 单品折扣规则列表
     */
    @GetMapping("/item-discounts")
    public ApiResponse<List<ItemDiscountRuleDTO>> getAllItemDiscounts() {
        log.debug("查询所有单品折扣规则");
        List<ItemDiscountRuleDTO> rules = promotionService.getAllItemDiscounts();
        log.debug("查询到 {} 条单品折扣规则", rules.size());
        return ApiResponse.success(rules);
    }
    
    // ==================== 满减折扣规则管理 ====================
    
    /**
     * 创建满减折扣规则
     * 
     * @param request 创建满减折扣请求
     * @return 满减折扣规则DTO
     */
    @PostMapping("/threshold-discounts")
    public ApiResponse<ThresholdDiscountRuleDTO> createThresholdDiscount(
            @Valid @RequestBody CreateThresholdDiscountRequest request) {
        log.info("创建满减折扣规则: name={}, thresholdAmount={}, reductionAmount={}", 
                request.getName(), request.getThresholdAmount(), request.getReductionAmount());
        
        ThresholdDiscountRuleDTO rule = promotionService.createThresholdDiscount(
                request.getName(),
                request.getThresholdAmount(),
                request.getReductionAmount(),
                request.getStackable() != null ? request.getStackable() : false,
                request.getThresholdUseOriginalPrice() != null ? request.getThresholdUseOriginalPrice() : false,
                3,  // Priority 3 (订单级，系统自动分配)
                request.getEffectiveFrom(),
                request.getEffectiveTo()
        );
        
        log.info("满减折扣规则创建成功: ruleId={}", rule.getId());
        return ApiResponse.success(rule);
    }
    
    /**
     * 查询所有满减折扣规则
     * 
     * @return 满减折扣规则列表
     */
    @GetMapping("/threshold-discounts")
    public ApiResponse<List<ThresholdDiscountRuleDTO>> getAllThresholdDiscounts() {
        log.debug("查询所有满减折扣规则（包括未启用的）");
        List<ThresholdDiscountRuleDTO> rules = promotionService.getAllThresholdDiscounts();
        log.debug("查询到 {} 条满减折扣规则", rules.size());
        return ApiResponse.success(rules);
    }
    
    /**
     * 查询当前生效的满减折扣规则（启用且在有效期内）
     * 用于前台展示当前活动
     * 
     * @return 满减折扣规则列表
     */
    @GetMapping("/threshold-discounts/effective")
    public ApiResponse<List<ThresholdDiscountRuleDTO>> getEffectiveThresholdDiscounts() {
        log.debug("查询当前生效的满减折扣规则");
        List<ThresholdDiscountRuleDTO> rules = promotionService.getEffectiveThresholdDiscounts();
        log.debug("查询到 {} 条生效的满减折扣规则", rules.size());
        return ApiResponse.success(rules);
    }
    // ==================== 促销规则通用管理 ====================
    
    /**
     * 启用促销规则
     * 
     * @param ruleId 规则ID
     * @return 成功响应
     */
    @PutMapping("/rules/{ruleId}/enable")
    public ApiResponse<Void> enableRule(@PathVariable String ruleId) {
        log.info("启用促销规则: ruleId={}", ruleId);
        promotionService.enableRule(ruleId);
        log.info("促销规则启用成功: ruleId={}", ruleId);
        return ApiResponse.success();
    }
    
    /**
     * 禁用促销规则
     * 
     * @param ruleId 规则ID
     * @return 成功响应
     */
    @PutMapping("/rules/{ruleId}/disable")
    public ApiResponse<Void> disableRule(@PathVariable String ruleId) {
        log.info("禁用促销规则: ruleId={}", ruleId);
        promotionService.disableRule(ruleId);
        log.info("促销规则禁用成功: ruleId={}", ruleId);
        return ApiResponse.success();
    }
    
    /**
     * 删除促销规则（通用接口）
     * 注意：具体的删除应该使用 /item-discounts/{id} 或 /threshold-discounts/{id}
     * 
     * @param ruleId 规则ID
     * @return 成功响应
     */
    @DeleteMapping("/rules/{ruleId}")
    public ApiResponse<Void> deleteRule(@PathVariable String ruleId) {
        log.info("删除促销规则: ruleId={}", ruleId);
        // 查询规则详情以确定类型
        PricingRuleDTO rule = promotionService.getRuleById(ruleId);
        
        // 根据规则类型调用相应的删除方法
        switch (rule.getType()) {
            case ITEM_DISCOUNT:
                promotionService.deleteItemDiscount(ruleId);
                break;
            case THRESHOLD_DISCOUNT:
                promotionService.deleteThresholdDiscount(ruleId);
                break;
            default:
                log.warn("未知的规则类型: ruleId={}, type={}", ruleId, rule.getType());
                break;
        }
        
        log.info("促销规则删除成功: ruleId={}", ruleId);
        return ApiResponse.success();
    }
    
    // ==================== 通用查询 ====================
    
    /**
     * 查询所有促销规则
     * 
     * @return 促销规则列表
     */
    @GetMapping
    public ApiResponse<List<PricingRuleDTO>> getAllPromotions() {
        log.debug("查询所有促销规则");
        List<PricingRuleDTO> rules = promotionService.getAllRules();
        log.debug("查询到 {} 条促销规则", rules.size());
        return ApiResponse.success(rules);
    }
    
    /**
     * 根据ID查询促销规则
     * 
     * @param ruleId 规则ID
     * @return 促销规则DTO
     */
    @GetMapping("/rules/{ruleId}")
    public ApiResponse<PricingRuleDTO> getRule(@PathVariable String ruleId) {
        log.debug("查询促销规则: ruleId={}", ruleId);
        PricingRuleDTO rule = promotionService.getRuleById(ruleId);
        return ApiResponse.success(rule);
    }
    
    /**
     * 查询所有促销规则（别名接口）
     * 
     * @return 促销规则列表
     */
    @GetMapping("/rules")
    public ApiResponse<List<PricingRuleDTO>> getAllRules() {
        log.debug("查询所有促销规则");
        List<PricingRuleDTO> rules = promotionService.getAllRules();
        log.debug("查询到 {} 条促销规则", rules.size());
        return ApiResponse.success(rules);
    }
    
    /**
     * 查询当前生效的所有促销规则
     * 
     * @return 促销规则列表（按优先级排序）
     */
    @GetMapping("/rules/effective")
    public ApiResponse<List<PricingRuleDTO>> getEffectiveRules() {
        log.debug("查询当前生效的促销规则");
        List<PricingRuleDTO> rules = promotionService.getCurrentEffectiveRules();
        log.debug("查询到 {} 条生效的促销规则", rules.size());
        return ApiResponse.success(rules);
    }
}

